package com.cloud.alibaba.common.util;

/**
 * @program: cloud-alibaba
 * @description: 邮件
 * @author: taoxinhuan
 * @create: 2021-03-24 11:05
 **/

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
public class EmailUtil {

    //发送邮件方法
    public static void sendEmail(String smtp, String from, String fromPassword, String to, String title, String html) {
        Properties prop = new Properties();
        prop.put("mail.host", smtp);
        prop.put("mail.transport.protocol", "smtp");
        // prop.put("mail.smtp.auth", "true");
        // prop.put("mail.transport.protocol", "smtps");
        // prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.port", "465");
        // prop.put("mail.smtp.connectiontimeout", 20000);
        // 发送逾期日报需要放在session前面 因为有调用接口操作 比较慢 session会过期
        // String a = overdueStra();
        // 使用java发送邮件5步骤
        // 1.创建sesssion
        Session session = Session.getInstance(prop);
        // 开启session的调试模式，可以查看当前邮件发送状态
        session.setDebug(true);
        // 2.通过session获取Transport对象（发送邮件的核心API）
        Transport ts;
        try {
            ts = session.getTransport();
            // 3.通过邮件用户名密码链接，阿里云默认是开启个人邮箱pop3、smtp协议的，所以无需在阿里云邮箱里设置
            ts.connect(from, fromPassword);
            Address toArr[] = new InternetAddress[1];
            toArr[0] = new InternetAddress(to);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, toArr);
            // Set Subject: 头字段
            message.setSubject(title);
            // 发送 HTML 消息, 可以插入html标签
            message.setContent(html, "text/html;charset=utf-8");
            ts.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            log.error("send mail error", e);
        }
    }

    /**
     * 远程获取要发送的信息
     */
    public static String getOneS() {
        //创建客户端对象
        //发起请求，接收响应对象
        HttpRequest httpRequest = HttpRequest.get("https://chp.shadiao.app/api.php");
        HttpResponse execute = httpRequest.execute();
        String body = execute.body();
        return body;
    }
}